package com.aiit.controller.admin;


import com.aiit.dto.EmployeePageQueryDTO;
import com.aiit.dto.TeaDTO;
import com.aiit.result.PageResult;
import com.aiit.result.Result;
import com.aiit.service.TeaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;


/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/tea")
@Slf4j
@Api(tags = "茶品相关接口")
public class TeaController {

    @Autowired
    private TeaService teaService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 茶叶分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("茶叶分页查询")
    public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO) {
        log.info("茶叶分页查询,参数为：{}", employeePageQueryDTO);
        PageResult pageResult = teaService.pageQuery(employeePageQueryDTO);
        return Result.success(pageResult);
    }


    @PutMapping("/update")
    @ApiOperation("编辑茶叶信息")
    @CacheEvict(cacheNames = "teaCache2", allEntries = true)
    public Result Update(@RequestBody TeaDTO teaDTO) {
        log.info("编辑茶叶信息:{}", teaDTO);
        teaService.update(teaDTO);

        cleanCache("tea_*");
        return Result.success();
    }

    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    @PostMapping("/save")
    @ApiOperation("新增茶叶")
    @CacheEvict(cacheNames = "teaCache2", key = "#teaDTO.id")
    public Result save(@RequestBody TeaDTO teaDTO) {
        log.info("新增茶叶：{}", teaDTO);
        System.out.println("当前线程的id:" + Thread.currentThread().getId());
        teaService.save(teaDTO);
        cleanCache("tea_*");
        return Result.success();

    }


    @DeleteMapping("/delete")
    @ApiOperation("删除茶叶")
    @CacheEvict(cacheNames = "teaCache2", allEntries = true)
    public Result delete(@RequestParam String name) {
        log.info("删除茶叶：{}", name);
        teaService.deleteTea(name);

        cleanCache("tea_*");
        return Result.success();
    }

}















